package com.gph.saviorframework.uitl;

import com.gph.saviorframework.common.model.PermissionType;
import com.gph.saviorframework.common.model.ResourcePermission;
import com.gph.saviorframework.security.service.ResourcePermissionService;
import com.gph.saviorframework.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by guopeihui on 2016/11/11.
 */
@Component
public class ResourcePermissionUtils {

    @Autowired
    private ResourcePermissionService resourcePermissionService;

    @Autowired
    private UserService userService;

    public List<String> getUserIdsByResourcePermission(String userId,String resourceType){
        //判断权限
        ResourcePermission resourcePermission = resourcePermissionService.getByUserIdAndResourceType(userId, resourceType);
        List<String> userIdList = new ArrayList<>();
        if(resourcePermission!=null){
            if(resourcePermission.getPermissionType().equals(PermissionType.ALL.getCode())){
                userIdList.addAll(userService.getIds());
            }
            else if(resourcePermission.getPermissionType().equals(PermissionType.ORGS.getCode())){
                String orgIds = resourcePermission.getOrgIds();
                if(orgIds.contains(",")){
                    String[] ids = orgIds.split(",");
                    for(String orgId : ids){
                        userIdList.addAll(userService.getUserIdsByOrgId(orgId));
                    }
                }
                else{
                    userIdList.addAll(userService.getUserIdsByOrgId(orgIds));
                }
            }
            else if(resourcePermission.getPermissionType().equals(PermissionType.SELF.getCode())){
                userIdList.add(userId);
            }
        }

        if(!userIdList.contains(userId)){
            userIdList.add(userId);
        }

        return userIdList;
    }
}
